package com.bupt.smart.ui.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bupt.smart.model.Goods;
import com.bupt.smart.model.Market;
import com.bupt.smart.model.OrderInfo;
import com.bupt.smart.network.APIManager;
import com.bupt.smart.smart.*;
import com.bupt.smart.ui.adapter.MarketAdapter;
import com.bupt.smart.ui.fragment.MarketFragment;
import com.bupt.smart.utils.GeneratetoBitmap;
import com.bupt.smart.utils.MarketHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by WWL on 2016/4/8.
 */
public class MarketActivity extends AppCompatActivity implements View.OnClickListener {

    private SimpleAdapter adapterCategory;//左右listview
    private MarketAdapter adapterGoods;
    private MyListView lvCategory;
    private MyListView lvGoods;
    private TextView tvShopName;
    private TextView tvShopInfo;
    private ImageView ivMarketImgMini;
    private Button btSubmit;
    private ImageView ivMarketBack;
    private View vLoading;
    private HashMap<String,HashMap<String,String>> orderInfo;
    private String strTotalPrice;
    private Market marketInfo = null;
    private Bitmap minipic;
    Intent getIntent =null;
    List<Goods> listGoods = null;
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_market);
        initData();
        btSubmit.setOnClickListener(this); //点击Submit实现跳转到订单页面OrderActivity
        ivMarketBack.setOnClickListener(this);//返回商城页面
        //填充两个listview的内容
        lvCategory = (MyListView)findViewById(R.id.list_market_l);
        lvGoods = (MyListView)findViewById(R.id.list_market_r);
        getGoodsfromDB(marketInfo.getID());
        adapterCategory = new SimpleAdapter(
                this,getCategory(1),
                R.layout.listview_market_l,
                new String[]{"category"},
                new int[]{R.id.category});
        lvCategory.setAdapter(adapterCategory);


    }
    /*
    * 初始化数据
    * */
        public void initData(){
            getIntent = this.getIntent();
            orderInfo = new HashMap<String,HashMap<String,String>>();
            ivMarketImgMini = (ImageView) findViewById(R.id.img);
            tvShopName = (TextView) findViewById(R.id.mingcheng);
            tvShopInfo =(TextView) findViewById(R.id.youhui);
            btSubmit = (Button) findViewById(R.id.market_definecart);
            strTotalPrice = ((TextView)findViewById(R.id.sumprice)).getText().toString();
            ivMarketBack = (ImageView)findViewById(R.id.market_back);
            vLoading = (View) findViewById(R.id.MarketActivityLoading);

            //显示商家信息
            marketInfo = (Market)getIntent.getSerializableExtra("market");
            Log.i("marketid",marketInfo.getID()+"");
            tvShopName.setText(marketInfo.getmarketname());
            tvShopInfo.setText(marketInfo.getmarketyouhui());
            minipic = (Bitmap)GeneratetoBitmap.GenerateImage(marketInfo.getMarketmini_str());
            ivMarketImgMini.setImageBitmap(minipic);
        }
    /*
    * author:wwl
    * 根据商家ID获取分类信息
    * param:id
    * */
    public static List<HashMap<String,Object>> getCategory(Integer id){
        List<HashMap<String,Object>> listmap = new ArrayList<HashMap<String, Object>>();
        HashMap<String,Object> map;
        List<String> list = new ArrayList<String>();
        //未连接mysql
        list.add("热销排行");
        list.add("今日特惠");
        list.add("食品");
        list.add("饮料");
        list.add("生活用品");
        list.add("居家百货");
        for(int i=0;i<list.size();i++) {
            map = new HashMap<String, Object>();
            map.put("category",list.get(i));
            listmap.add(map);
        }
        return listmap;
    }
    /*
    * author:wwl
    * 计算购物车总金额和总数量
    * para:sumprice choice(=1 add   =2 sub)
    *
    * */
    public  void shopCart(String sumprice,int choice){
        TextView numtext = (TextView)findViewById(R.id.sumnum);
        TextView pricetext = (TextView)findViewById(R.id.sumprice);
        DecimalFormat df=new DecimalFormat(".##");
        switch(choice){
            case 1:{
                if(numtext.getText().equals(""))
                    numtext.setText(1+"");
                else
                numtext.setText(Integer.parseInt(numtext.getText().toString())+1+"");
                String sum;
                if(pricetext.getText().equals(""))
                    sum = "0.00";
                 else
                    sum = df.format(Double.parseDouble(pricetext.getText().toString()) + Double.parseDouble(sumprice));
                    pricetext.setText(sum);
                strTotalPrice = sum;
            }
            break;
            case 2:{
                numtext.setText(Integer.parseInt(numtext.getText().toString())-1+"");
                String sum = df.format(Double.parseDouble(pricetext.getText().toString()) - Double.parseDouble(sumprice));
                if(sum.equals(".0"))
                    pricetext.setText("0.00");
                else
                    pricetext.setText(sum);
                strTotalPrice = sum;
            }
            break;
            default:{}
        }

    }
    @Override
    public void onClick(View v) {
        Intent intent;
        switch(v.getId()){
            //返回商城
            case R.id.market_back:
                intent = new Intent(MarketActivity.this,TabActivity.class);
                intent.putExtra("fragment",2);
                this.startActivity(intent);
                break;
            //提交订单
            case R.id.market_definecart:
                if(orderInfo.size() == 0){  //无商品,不跳转
                    Toast toast = Toast.makeText(MarketActivity.this,"购物车为空",Toast.LENGTH_LONG);
                    toast.show();
                }
                else{
                    intent = new Intent(MarketActivity.this,OrderActivity.class);
                    //保存订单信息
                    intent.putExtras(getIntent);
                    intent.putExtra("orderInfo", orderInfo);
                    intent.putExtra("totalprice", strTotalPrice);
                    MarketActivity.this.startActivity(intent);
                }
                break;

        }
    }
    /*
    * author:wwl
    * 用户在店家+、- 按钮时,记录商品ID，数量，名称，单价
    * @para type(=1 add  =2 sub)
    * */
    public  void setCart(int type,String ID,String name,String price){
        switch (type){
            case 1:{
                HashMap<String,String> temp = this.orderInfo.get(ID);
                if(temp!=null){
                int oldnum = Integer.parseInt(temp.get("num"));
                temp.put("num",(oldnum+1)+"");
                    Log.i("num",temp.get("num"));
                }
                else{   //首次加入商品
                    temp = new HashMap<String,String>();
                    temp.put("num",1+"");
                    temp.put("name",name);
                    temp.put("price",price);
                    this.orderInfo.put(ID,temp);
                    Log.i("num", temp.get("num"));
                }
            }break;
            case 2:{
                HashMap<String,String> temp = this.orderInfo.get(ID);
                if(temp!=null){
                    int oldnum = Integer.parseInt(temp.get("num"));
                    oldnum--;
                    if(oldnum<=0)   //商品全部移出购物车
                    {
                        this.orderInfo.remove(ID);
                        Log.i("num", temp.get("num"));
                    }
                    else
                    {
                        temp.put("num",(oldnum+""));
                        Log.i("num", temp.get("num"));
                    }
                }
            }break;
            default:break;
        }
    }
   public  void getGoodsfromDB(int id) {
        Call<List<Goods>> call = APIManager.getMarketAPI().getGoods(marketInfo.getID());
        call.enqueue(new Callback<List<Goods>>() {
            @Override
            public void onResponse(Call<List<Goods>> call, Response<List<Goods>> response) {
                if(response.body() != null){
                    listGoods = response.body();
                    for(int i=0;i<listGoods.size();i++)
                        listGoods.get(i).setBitmapGood(GeneratetoBitmap.GenerateImage(listGoods.get(i).getShoppic_str()));

                    lvGoods.setVisibility(View.VISIBLE);
                    vLoading.setVisibility(View.GONE);
                    adapterGoods = new MarketAdapter(MarketActivity.this,listGoods);
                    lvGoods.setAdapter(adapterGoods);
                }
            }

            @Override
            public void onFailure(Call<List<Goods>> call, Throwable t) {
                Toast toast = Toast.makeText(MarketActivity.this,"获取商品信息失败！",Toast.LENGTH_LONG);
                toast.show();
            }
        });
        }


    }
